package net.trombonium.steroid;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

public class Manager extends BroadcastReceiver{
	private static final int REQUEST_CODE = 0;
	private static final String TAG = "Manager";
	
	public Manager(){}

	@Override
	public void onReceive(Context context, Intent intent) {
		if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
			//Log.i(TAG, "*********************** "+intent.getDataString()+" ****************");
			(new DBHelper(context)).parseCronjobs(null);
			setAlarms(context);
			
		}
		else{
			Log.i(TAG, String.valueOf(intent.getIntExtra(WAInterface.TODO, 100)));
			switch(intent.getIntExtra(WAInterface.TODO, -1)){
			case WAInterface.GET_SURVEYS:
				if(Calendar.getInstance().get(Calendar.MINUTE)==0){
					Log.i(TAG, "Parsing cronjobs...");
					(new DBHelper(context)).parseCronjobs(null);
				}
				Intent getSurveyIntent = new Intent(context, WAInterface.class);
				getSurveyIntent.putExtra(WAInterface.TODO, WAInterface.GET_SURVEYS);
				context.startService(getSurveyIntent);
				return;
			}
		}
		
	}
	
	public void setAlarms(Context context){
		Log.i(TAG, "Setting alarms...");
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//		alarmManager.cancel(PendingIntent.getBroadcast(context, 0, new Intent(context, Manager.class), 0));
		
		Calendar cal = Calendar.getInstance();
		int offset = cal.get(Calendar.MINUTE)%5;
		cal.add(Calendar.MINUTE, 5-offset);
		cal.set(Calendar.SECOND, 0);
		
		Intent intent = new Intent(context, Manager.class);
		intent.putExtra(WAInterface.TODO, WAInterface.GET_SURVEYS);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (5*60*1000), pendingIntent);
//		
//		
//		Intent intent2 = new Intent(context, Manager.class);
//		intent2.putExtra(WAInterface.TODO, WAInterface.CRONJOBS);
//		PendingIntent cronjobIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent2, 0);

//		AlarmManager alarmManager2 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//		alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (10*1000), cronjobIntent);
//		alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10*1000), (10*1000), cronjobIntent);
		
	}
	
	/*
	public void parseCronjobs(Context context){
		(new DBHelper.)
	}
	*/
}
